package com.marvels.financial.collection.service.impl;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.fintech.third.service.message.SmsService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.marvels.common.constants.MarvelsConstant;
import com.marvels.common.constants.PageConstant;
import com.marvels.common.dto.MarvelsResultDTO;
import com.marvels.common.dto.UserDTO;
import com.marvels.common.dto.pay.McfePaymentUserBindCard;
import com.marvels.common.exception.MarvelsBusinessException;
import com.marvels.common.exception.MarvelsErrorCode;
import com.marvels.common.utils.CacheUtils;
import com.marvels.common.utils.CommonProperties;
import com.marvels.common.utils.DateUtils;
import com.marvels.common.utils.MarvelsLogUtil;
import com.marvels.common.utils.ResourceProperties;
import com.marvels.common.utils.ServerProperties;
import com.marvels.financial.collection.dao.McfeCollecteActionRecordDao;
import com.marvels.financial.collection.dao.McfeElectricCollecteResultDao;
import com.marvels.financial.collection.dao.McfeOverdueCollectionActionCodeMapper;
import com.marvels.financial.collection.dao.McfeOverdueCollectionActionStatusMapper;
import com.marvels.financial.collection.dao.McfeOverdueCollectionCollectionVisitMapper;
import com.marvels.financial.collection.dao.McfeOverdueCollectionMapper;
import com.marvels.financial.collection.dao.McfeOverdueCollectionRiskCategoryMapper;
import com.marvels.financial.collection.dao.McfeOverdueCollectionVerificationMapper;
import com.marvels.financial.collection.dao.McfeOverdueManageMapper;
import com.marvels.financial.collection.dao.OverdueCollectMapper;
import com.marvels.financial.collection.dto.CaseInfoDTO;
import com.marvels.financial.collection.dto.CollectAccountDTO;
import com.marvels.financial.collection.dto.CollectCommonModularInfoDTO;
import com.marvels.financial.collection.dto.CollectListConditionDTO;
import com.marvels.financial.collection.dto.CollectListInfoDTO;
import com.marvels.financial.collection.dto.CollectTransferDTO;
import com.marvels.financial.collection.dto.CommonConditionDTO;
import com.marvels.financial.collection.dto.McfeCollecteActionRecordDTO;
import com.marvels.financial.collection.dto.McfeElectricCollecteResultDTO;
import com.marvels.financial.collection.dto.McfeOverdueCollectionActionCodeDTO;
import com.marvels.financial.collection.dto.McfeOverdueCollectionActionStatusDTO;
import com.marvels.financial.collection.dto.McfeOverdueCollectionCollectionVisitDTO;
import com.marvels.financial.collection.dto.McfeOverdueCollectionDTO;
import com.marvels.financial.collection.dto.McfeOverdueCollectionRiskCategoryDTO;
import com.marvels.financial.collection.dto.McfeOverdueCollectionVerificationDTO;
import com.marvels.financial.collection.dto.MclaRelationInfoDTO;
import com.marvels.financial.collection.dto.OnlineDeductionDto;
import com.marvels.financial.collection.dto.OverDueCollectContractDTO;
import com.marvels.financial.collection.dto.OverDueTransInfoDTO;
import com.marvels.financial.collection.service.CollectManageApi;
import com.marvels.financial.consum.FinancialConsumerApproveApi;
import com.marvels.financial.consum.FinancialConsumerLoanApplyApi;
import com.marvels.financial.consum.FinancialConsumerProductApi;
import com.marvels.financial.funds.dao.IFundDao;
import com.marvels.financial.funds.dto.FundDTO;
import com.marvels.financial.loan.dao.McfeCustomerLoanContractDao;
import com.marvels.financial.loan.dao.McfeCustomerRepaymentPlanDao;
import com.marvels.financial.loan.dto.McamLoanApplyInfoDTO;
import com.marvels.financial.loan.dto.McfeCustomerLoanContractDTO;
import com.marvels.financial.loan.dto.McfeCustomerRepaymentPlanDTO;
import com.marvels.financial.loan.dto.MclaLoanApplyLinkmanDTO;
import com.marvels.financial.loan.dto.McptChannelDto;
import com.marvels.financial.loan.dto.McptProductType;
import com.marvels.financial.loan.service.HandleWithholdApi;
import com.marvels.system.permission.dto.SysRoleDTO;
import com.marvels.system.permission.dto.SysUserDTO;
import com.marvels.system.permission.service.SysRoleService;

/**
 * 催收管理实现
 * 
 * @author tangpw
 *
 */
@Service
public class CollectManageImpl implements CollectManageApi {

	@Autowired
	private FinancialConsumerProductApi consumerProductApi;

	@Autowired
	private OverdueCollectMapper collectMapper;

	@Autowired
	private McfeOverdueCollectionMapper overdueMapper;
	
	@Autowired
	private IFundDao fundDTO;

	@Autowired
	private McfeOverdueCollectionRiskCategoryMapper categoryMapper;

	@Autowired
	private McfeOverdueCollectionActionStatusMapper actionMapper;

	@Autowired
	private McfeOverdueCollectionActionCodeMapper codeMapper;

	@Autowired
	private McfeOverdueCollectionVerificationMapper verificationMapper;

	@Autowired
	private McfeOverdueCollectionCollectionVisitMapper visitMapper;

	@Autowired
	private McfeCollecteActionRecordDao recordDao;

	@Autowired
	private FinancialConsumerLoanApplyApi loanApplyApi;

	@Autowired
	private McfeElectricCollecteResultDao resultDao;

//	@Autowired
//	private CommonProperties commonProperties;
	@Autowired
	private FinancialConsumerApproveApi consumerApproveApi;
	@Autowired
	private McfeOverdueManageMapper mcfeOverdueManageMapper;
	
	@Autowired
	private McfeCustomerLoanContractDao contractDao;
	@Autowired
	private HandleWithholdApi handleWithholdApi;
	@Autowired
	private McfeCustomerRepaymentPlanDao planDao;
	
	@Autowired
	private SmsService smsService;
	
	@Autowired
	private SysRoleService sysRoleService;
	@Value("${config.properties.path}")
	private  String configPropertiesPath;
	
	@Override
	public MarvelsResultDTO collectCondition() throws MarvelsBusinessException {
		// 产品列表
		List<McptProductType> productList = consumerProductApi.mcptProductTypeInfo(new McptProductType());
		// 渠道列表
		List<McptChannelDto> channelList = consumerProductApi.mcptChannelAllInfo(new McptChannelDto());
		// 资金源
		List<FundDTO> fundList = fundDTO.select(new FundDTO());
		// 分险参数
		List<McfeOverdueCollectionRiskCategoryDTO> categoryList = categoryMapper
				.riskList(new McfeOverdueCollectionRiskCategoryDTO());

		// 行动结果
		List<McfeOverdueCollectionActionStatusDTO> actionReultList = actionMapper
				.actionList(new McfeOverdueCollectionActionStatusDTO());
		// 行动代码
		List<McfeOverdueCollectionActionCodeDTO> actionCodeList = codeMapper
				.actionCodeList(new McfeOverdueCollectionActionCodeDTO());
		Map<String, Object> map = new HashMap<>();
		map.put("productList", productList);
		map.put("channelList", channelList);
		map.put("fundList", fundList);
		map.put("categoryList", categoryList);
		map.put("actionReultList", actionReultList);
		map.put("actionCodeList", actionCodeList);
		return MarvelsResultDTO.getResult(MarvelsErrorCode.SUCCESS.getValue(), MarvelsErrorCode.SUCCESS.getDesc(), map);
	}

	@Override
	public Map<String, Object> collectList(CollectListConditionDTO condition) throws MarvelsBusinessException {
		UserDTO user = CacheUtils.getCacheUser();
		//在白名单或者是催收主管，则查所有数据
		String whiteStr = ResourceProperties.getCollectionQueryWhiteList();
		List<String> whiteList = new ArrayList<>();
		if(org.apache.commons.lang3.StringUtils.isNotEmpty(whiteStr)){
			whiteList = new ArrayList<String>(Arrays.asList(whiteStr.split(",")));
		}
		List<String> roleCodes = new ArrayList<String>();
		roleCodes.add("CSZG01");
		List<SysRoleDTO> roleList = sysRoleService.getSysRolesByRoleCodes(roleCodes);
		if(roleList != null && roleList.size() > 0){
			for (SysUserDTO sysUserDTO : roleList.get(0).getSysUsers()) {
				whiteList.add(sysUserDTO.getUserCode());
			}
		}
		if(!whiteList.contains(user.getUserCode())){
			condition.setCurrentUser(user.getUserCode());
		}
		
		int pageSize = condition.getPageSize();
		int pageNum = condition.getPageNum();
		if (pageSize < 1) {
			pageSize = PageConstant.PAGESIZE;
		}
		if (pageNum < 1) {
			pageNum = PageConstant.CURRPAGE;
		}
		PageHelper.startPage(pageNum, pageSize);

		String overdueRemindersFlag  = ServerProperties.getValue(configPropertiesPath, "common.properties", "overdue.reminders.flag");
		condition.setOverdueRemindersFlag(StringUtils.isEmpty(overdueRemindersFlag) ? "0" : overdueRemindersFlag);
		
		Page<CollectListInfoDTO> list = collectMapper.collectList(condition);
		Map<String, Object> map=new HashMap<String, Object>();
		map.put("data",list);
		map.put("total",list.getTotal());
		CollectListInfoDTO dto=collectMapper.collectAmountStatic(condition);
		List<CollectListInfoDTO> staticList=new ArrayList<CollectListInfoDTO>();
		staticList.add(dto);
		map.put("static",staticList);
		return map;
	}
	
	@Override
	public Map<String, Object> collectTransferList(CollectListConditionDTO condition) throws MarvelsBusinessException {
		int pageSize = condition.getPageSize();
		int pageNum = condition.getPageNum();
		if (pageSize < 1) {
			pageSize = PageConstant.PAGESIZE;
		}
		if (pageNum < 1) {
			pageNum = PageConstant.CURRPAGE;
		}
		PageHelper.startPage(pageNum, pageSize);
		String overdueRemindersFlag  = ServerProperties.getValue(configPropertiesPath, "common.properties", "overdue.reminders.flag");
		condition.setOverdueRemindersFlag(StringUtils.isEmpty(overdueRemindersFlag) ? "0" : overdueRemindersFlag);
		Page<CollectListInfoDTO> list = collectMapper.collectList(condition);
		Map<String, Object> map=new HashMap<String, Object>();
		map.put("data",list);
		map.put("total",list.getTotal());
		CollectListInfoDTO dto=collectMapper.collectAmountStatic(condition);
		List<CollectListInfoDTO> staticList=new ArrayList<CollectListInfoDTO>();
		staticList.add(dto);
		map.put("static",staticList);
		return map;
	}

	@Override
	public HSSFWorkbook downLoadExcel(CollectListConditionDTO condition) throws MarvelsBusinessException {
		UserDTO user = CacheUtils.getCacheUser();
		//在白名单或者是催收主管，则查所有数据
		String whiteStr = ResourceProperties.getCollectionQueryWhiteList();
		List<String> whiteList = new ArrayList<>();
		if(StringUtils.isNotEmpty(whiteStr)){
			whiteList = new ArrayList<String>(Arrays.asList(whiteStr.split(",")));
		}
		List<String> roleCodes = new ArrayList<String>();
		roleCodes.add("CSZG01");
		List<SysRoleDTO> roleList = sysRoleService.getSysRolesByRoleCodes(roleCodes);
		if(roleList != null && roleList.size() > 0){
			for (SysUserDTO sysUserDTO : roleList.get(0).getSysUsers()) {
				whiteList.add(sysUserDTO.getUserCode());
			}
		}
		if(!whiteList.contains(user.getUserCode())){
			condition.setCurrentUser(user.getUserCode());
		}
		String overdueRemindersFlag  = ServerProperties.getValue(configPropertiesPath, "common.properties", "overdue.reminders.flag");
		condition.setOverdueRemindersFlag(StringUtils.isEmpty(overdueRemindersFlag) ? "0" : overdueRemindersFlag);
		Page<CollectListInfoDTO> list = collectMapper.collectList(condition);
		HSSFWorkbook workbook = new HSSFWorkbook();
		HSSFSheet sheet = workbook.createSheet("firstSheet");
		HSSFRow row = sheet.createRow((int) 0);
		sheet.setDefaultColumnWidth(10);
		// 创建单元格，并设置值表头 设置表头居中
		HSSFCellStyle style = workbook.createCellStyle();
		// 居中格式、加粗
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		org.apache.poi.hssf.usermodel.HSSFFont font = workbook.createFont();
		font.setFontHeightInPoints((short) 11);
		font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
		style.setBorderBottom((short) 1);// 下边框
		style.setBorderLeft((short) 1);// 左边框
		style.setBorderRight((short) 1);// 右边框
		style.setBorderTop((short) 1);// 上边框
		style.setLocked(true);
		style.setFont(font);
		// 设置表内容格式
		HSSFCellStyle style2 = workbook.createCellStyle();
		style2.setBorderBottom((short) 1);// 下边框
		style2.setBorderLeft((short) 1);// 左边框
		style2.setBorderRight((short) 1);// 右边框
		style2.setBorderTop((short) 1);// 上边框
		style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		HSSFCell cell = row.createCell(0);
		cell.setCellValue("序号");
		cell.setCellStyle(style);
		cell = row.createCell(1);
		cell.setCellValue("借款人");
		cell.setCellStyle(style);
		cell = row.createCell(2);
		cell.setCellValue("手机号");
		cell.setCellStyle(style);
		cell = row.createCell(3);
		cell.setCellValue("放款时间");
		cell.setCellStyle(style);
		cell = row.createCell(4);
		cell.setCellValue("放款金额");
		cell.setCellStyle(style);
		cell = row.createCell(5);
		cell.setCellValue("还款日期");
		cell.setCellStyle(style);
		cell = row.createCell(6);
		cell.setCellValue("最迟还款日期");
		cell.setCellStyle(style);
		cell = row.createCell(7);
		cell.setCellValue("应还本金");
		cell.setCellStyle(style);
		cell = row.createCell(8);
		cell.setCellValue("滞纳金");
		cell.setCellStyle(style);
		cell = row.createCell(9);
		cell.setCellValue("逾期天数");
		cell.setCellStyle(style);
		cell = row.createCell(10);
		cell.setCellValue("状态");
		cell.setCellStyle(style);
		cell = row.createCell(11);
		cell.setCellValue("还款次数");
		cell.setCellStyle(style);
		cell = row.createCell(12);
		cell.setCellValue("联系次数");
		cell.setCellStyle(style);
		cell = row.createCell(13);
		cell.setCellValue("原催收");
		cell.setCellStyle(style);
		cell = row.createCell(14);
		cell.setCellValue("现催收");
		cell.setCellStyle(style);
		cell = row.createCell(15);
		cell.setCellValue("备注");
		cell.setCellStyle(style);
		if (null != list && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				CollectListInfoDTO dto = list.get(i);
				row = sheet.createRow((int) i + 1);
				// 创建单元格，并设置值
				row.createCell(0).setCellValue(String.valueOf(i + 1));
				row.createCell(1).setCellValue(dto.getCustName());
				row.createCell(2).setCellValue(dto.getMobile() + "");
				row.createCell(3).setCellValue(DateUtils.getDateYYYYMMDDHHMMSS(dto.getLoanTime()));
				row.createCell(4).setCellValue(dto.getLoanAmount() + "");
				row.createCell(5).setCellValue(DateUtils.getDateYYYY_MM_DD(dto.getRepaymentDate()));
				row.createCell(6).setCellValue(DateUtils.getDateYYYY_MM_DD(dto.getRepaymentDateLate()));
				row.createCell(7).setCellValue(dto.getPaymentPrincipal() + "");
				row.createCell(8).setCellValue(dto.getLateFee() + "");
				row.createCell(9).setCellValue(dto.getOverdueDays() + "");
				row.createCell(10).setCellValue(dto.getLastpaymentResult());
				row.createCell(11).setCellValue(dto.getRepaymentNum() == null ? "0" : String.valueOf(dto.getRepaymentNum()));
				row.createCell(12).setCellValue(dto.getContactNumber() == null ? "0" : String.valueOf(dto.getContactNumber()));
				row.createCell(13).setCellValue(dto.getOriginalCollectMan());
				row.createCell(14).setCellValue(dto.getCurrCollectMan());
				row.createCell(15).setCellValue(dto.getRemarks());
			}
		}
		return workbook;
	}

	@Override
	public HSSFWorkbook downOutsideExcel(CollectListConditionDTO condition) throws MarvelsBusinessException {
		String overdueRemindersFlag  = ServerProperties.getValue(configPropertiesPath, "common.properties", "overdue.reminders.flag");
		condition.setOverdueRemindersFlag(StringUtils.isEmpty(overdueRemindersFlag) ? "0" : overdueRemindersFlag);
		Page<CollectListInfoDTO> list = collectMapper.collectList(condition);
		HSSFWorkbook workbook = new HSSFWorkbook();
		HSSFSheet sheet = workbook.createSheet("firstSheet");
		HSSFRow row = sheet.createRow((int) 0);
		sheet.setDefaultColumnWidth(10);
		// 创建单元格，并设置值表头 设置表头居中
		HSSFCellStyle style = workbook.createCellStyle();
		// 居中格式、加粗
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		org.apache.poi.hssf.usermodel.HSSFFont font = workbook.createFont();
		font.setFontHeightInPoints((short) 11);
		font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
		style.setBorderBottom((short) 1);// 下边框
		style.setBorderLeft((short) 1);// 左边框
		style.setBorderRight((short) 1);// 右边框
		style.setBorderTop((short) 1);// 上边框
		style.setLocked(true);
		style.setFont(font);
		// 设置表内容格式
		HSSFCellStyle style2 = workbook.createCellStyle();
		style2.setBorderBottom((short) 1);// 下边框
		style2.setBorderLeft((short) 1);// 左边框
		style2.setBorderRight((short) 1);// 右边框
		style2.setBorderTop((short) 1);// 上边框
		style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		HSSFCell cell = row.createCell(0);
		cell.setCellValue("序号");
		cell.setCellStyle(style);
		cell = row.createCell(1);
		cell.setCellValue("借款人");
		cell.setCellStyle(style);
		cell = row.createCell(2);
		cell.setCellValue("贷款金额");
		cell.setCellStyle(style);
		cell = row.createCell(3);
		cell.setCellValue("贷款日期");
		cell.setCellStyle(style);
		cell = row.createCell(4);
		cell.setCellValue("当前逾期期数");
		cell.setCellStyle(style);
		cell = row.createCell(5);
		cell.setCellValue("客户身份证号");
		cell.setCellStyle(style);
		cell = row.createCell(6);
		cell.setCellValue("电话号码");
		cell.setCellStyle(style);
		cell = row.createCell(7);
		cell.setCellValue("当前应还款总金额");
		cell.setCellStyle(style);
		cell = row.createCell(8);
		cell.setCellValue("滞纳金");
		cell.setCellStyle(style);
		cell = row.createCell(9);
		cell.setCellValue("逾期天数");
		cell.setCellStyle(style);
		cell = row.createCell(10);
		cell.setCellValue("应还款日期");
		cell.setCellStyle(style);
		cell = row.createCell(11);
		cell.setCellValue("贷款产品");
		cell.setCellStyle(style);
		cell = row.createCell(12);
		cell.setCellValue("最近一次行动结果");
		cell.setCellStyle(style);
		cell = row.createCell(13);
		cell.setCellValue("当前催收人员");
		cell.setCellStyle(style);
		cell = row.createCell(14);
		cell.setCellValue("最近一次行动代码");
		cell.setCellStyle(style);
		cell = row.createCell(15);
		cell.setCellValue("最近一次行动时间");
		cell.setCellStyle(style);
		cell = row.createCell(16);
		cell.setCellValue("最近一次还款结果");
		cell.setCellStyle(style);
		if (null != list && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				CollectListInfoDTO dto = list.get(i);
				row = sheet.createRow((int) i + 1);
				// 创建单元格，并设置值
				row.createCell(0).setCellValue(String.valueOf(i + 1));
				row.createCell(1).setCellValue(dto.getCustName());
				row.createCell(2).setCellValue(dto.getLoanAmount() + "");
				row.createCell(3).setCellValue(DateUtils.getDateYYYY_MM_DD(dto.getLoanDate()));
				row.createCell(4).setCellValue(dto.getCurrOverduePeriod());
				row.createCell(5).setCellValue(dto.getCustIdNumber());
				row.createCell(6).setCellValue(dto.getMobile());
				row.createCell(7).setCellValue(dto.getCurrPaymentAmount() + "");
				row.createCell(8).setCellValue(dto.getLateFee() + "");
				row.createCell(9).setCellValue(dto.getOverdueDays());
				row.createCell(10).setCellValue(DateUtils.getDateYYYY_MM_DD(dto.getRepaymentDate()));
				row.createCell(11).setCellValue(dto.getProductName());
				row.createCell(12).setCellValue(dto.getLastActionResult());
				row.createCell(13).setCellValue(dto.getCurrCollectMan());
				row.createCell(14).setCellValue(dto.getLastActionCode());
				row.createCell(15).setCellValue(DateUtils.getDateYYYY_MM_DD(dto.getLastActionDate()));
				row.createCell(16).setCellValue(dto.getLastpaymentResult());
			}
		}
		return workbook;
	}

	@Override
	public CollectCommonModularInfoDTO commonModularInfo(CollectListConditionDTO condition)
			throws MarvelsBusinessException {
		String overdueCode = condition.getOverdueCode();
		// 电催录入信息
		McfeOverdueCollectionVerificationDTO verificationDTO = new McfeOverdueCollectionVerificationDTO();
		verificationDTO.setOverdueCode(overdueCode);
		List<McfeOverdueCollectionVerificationDTO> verificationList = verificationMapper
				.verificationList(verificationDTO);
		// 催收外访信息
		McfeOverdueCollectionCollectionVisitDTO visitDTO = new McfeOverdueCollectionCollectionVisitDTO();
		visitDTO.setOverdueCode(overdueCode);
		List<McfeOverdueCollectionCollectionVisitDTO> visitList = visitMapper.visitList(visitDTO);
		
		CollectCommonModularInfoDTO modularInfoDTO = new CollectCommonModularInfoDTO();
		modularInfoDTO.setVerficationList(verificationList);
		modularInfoDTO.setVisitList(visitList);
		// 联系人
		List<MclaRelationInfoDTO> shipList = loanApplyApi.shipList(new MclaRelationInfoDTO());
		/*MarvelsLogUtil.getInstance().info(">>>>>relationList联系人关系基返回数据:"+JSONObject.fromObject(shipList));*/
		// 循环将联系人的手机号码 姓名 填充
		MclaLoanApplyLinkmanDTO linkmanDTO = new MclaLoanApplyLinkmanDTO();
		linkmanDTO.setLoanId(condition.getLoanId());
		List<MclaLoanApplyLinkmanDTO> linkManList = loanApplyApi.selectByLoanId(linkmanDTO);
		if (null != shipList && shipList.size() > 0) {
			for (MclaRelationInfoDTO info : shipList) {
				if (null != linkManList && linkManList.size() > 0) {
					for (MclaLoanApplyLinkmanDTO linkMan : linkManList) {
						if ("0".equals(linkMan.getRelationType())) {// 亲属
							if (info.getCode().equals(linkMan.getRelationId())) {
								info.setRelationName(linkMan.getLinkmanName());
								info.setRelationMobile(linkMan.getLinkmanMobile());
							}
						} else {// 其他
							info.setRelationName(linkMan.getLinkmanName());
							info.setRelationMobile(linkMan.getLinkmanMobile());
						}
					}
				}

			}
		}
		modularInfoDTO.setRelationList(shipList);
		// 行动结果
		List<McfeOverdueCollectionActionStatusDTO> actionReultList = actionReultList(
				new McfeOverdueCollectionActionStatusDTO());
		// 行动代码
		List<McfeOverdueCollectionActionCodeDTO> actionCodeList = actionCodeList(
				new McfeOverdueCollectionActionCodeDTO());
		modularInfoDTO.setCodeList(actionCodeList);
		modularInfoDTO.setActionResultList(actionReultList);
		// 电催收结果
		modularInfoDTO.setResultList(resultDao.resultList(new McfeElectricCollecteResultDTO()));
		return modularInfoDTO;

	}

	@Override
	public void addActionInfo(McfeCollecteActionRecordDTO dto) throws MarvelsBusinessException {
		UserDTO user = CacheUtils.getCacheUser();
		dto.setActionResult("Y");
		dto.setIsFinished("N");
		dto.setCreatedBy(user.getUserCode());
		dto.setActionUser(user.getUserCode());
		dto.setCreatedDate(new Date());
		dto.setUpdatedBy(user.getUserCode());
		dto.setUpdatedDate(new Date());
		int count = recordDao.insertSelective(dto);
		if (count < 1) {
			throw new MarvelsBusinessException("新增失败");
		}
		
		//更新逾期催收记录
		McfeOverdueCollectionDTO collectDTO=new McfeOverdueCollectionDTO();
		collectDTO.setOverdueCode(dto.getOverdueCode());
		collectDTO.setLastActionCode(dto.getActionCode());
		collectDTO.setLastActionName(dto.getActionName());
		collectDTO.setAssignee(user.getUserCode());
		collectDTO.setLastActionTime(new SimpleDateFormat("yyyy-MM-dd").format(dto.getMeetDate()==null? new Date():dto.getMeetDate()));
		collectDTO.setLastActionResultCode(dto.getActionStatusCode());
		collectDTO.setLastActionUser(user.getUserCode());
		collectDTO.setLastActionResultName(dto.getActionStatusName());
		collectDTO.setUpdatedBy(user.getUserCode());
		collectDTO.setUpdatedDate(new Date());
		int countCollect=collectMapper.updateByOverdueCode(collectDTO);
		if(countCollect<1){
			throw new MarvelsBusinessException("持久化催收信息失败");
		}
		
	}

	@Override
	public List<McfeOverdueCollectionActionCodeDTO> actionCodeList(McfeOverdueCollectionActionCodeDTO dto) {
		List<McfeOverdueCollectionActionCodeDTO> actionCodeList = null;
		String redisKey = MarvelsConstant.OVERDUE_COLLECT_ACTION_CODE;
		Object object = CacheUtils.getCacheObject(redisKey);
		if (null != object) {
			actionCodeList = (List<McfeOverdueCollectionActionCodeDTO>) object;
		}
		if(CollectionUtils.isEmpty(actionCodeList)){
			actionCodeList = codeMapper.actionCodeList(dto);
			CacheUtils.cacheObject(MarvelsConstant.OVERDUE_COLLECT_ACTION_CODE, actionCodeList);
		}
		return actionCodeList;
	}

	@Override
	public List<McfeOverdueCollectionActionStatusDTO> actionReultList(McfeOverdueCollectionActionStatusDTO dto) {
		List<McfeOverdueCollectionActionStatusDTO> actionReultList = null;
		String redisKey = MarvelsConstant.OVERDUE_COLLECT_ACTION_RESULT;
		Object object = CacheUtils.getCacheObject(redisKey);
		if (null != object) {
			actionReultList = (List<McfeOverdueCollectionActionStatusDTO>) object;
		} 
		if(CollectionUtils.isEmpty(actionReultList)) {
			actionReultList = actionMapper.actionList(dto);
			CacheUtils.cacheObject(MarvelsConstant.OVERDUE_COLLECT_ACTION_RESULT, actionReultList);
		}
		
		return actionReultList;
	}

	@Override
	public void addElectricCollectInfo(McfeOverdueCollectionVerificationDTO dto) throws MarvelsBusinessException {
		UserDTO user = CacheUtils.getCacheUser();
		dto.setCreatedBy(user.getUserCode());
		dto.setCreatedDate(new Date());
		dto.setUpdateTime(new Date());
		dto.setUpdatedBy(user.getUserCode());
		dto.setUpdatedDate(new Date());
		int count=verificationMapper.insertSelective(dto);
		if(count<1){
			throw new MarvelsBusinessException("新增失败");
		}
	}

	@Override
	public void modifyElectricCollectInfo(McfeOverdueCollectionVerificationDTO dto) throws MarvelsBusinessException {
		UserDTO user = CacheUtils.getCacheUser();
		dto.setUpdatedBy(user.getUserCode());
		dto.setUpdatedDate(new Date());
		int count=verificationMapper.updateInfo(dto);
		if(count<1){
			throw new MarvelsBusinessException("修改失败");
		}
		
	}

	@Override
	public void addCollectVisitInfo(McfeOverdueCollectionCollectionVisitDTO dto) throws MarvelsBusinessException {
		UserDTO user= CacheUtils.getCacheUser();
		if(dto.getId()==null){
			dto.setCreatedBy(user.getUserCode());
			dto.setCreatedDate(new Date());
			dto.setUpdatedBy(user.getUserCode());
			dto.setUpdatedDate(new Date());
			int count=visitMapper.insertSelective(dto);
			if(count<1){
				throw new MarvelsBusinessException("新增失败");
			}
		}else{
			dto.setCreatedBy(user.getUserCode());
			dto.setCreatedDate(new Date());
			dto.setUpdatedBy(user.getUserCode());
			dto.setUpdatedDate(new Date());
			int count=visitMapper.updateVisitInfo(dto);
			if(count<1){
				throw new MarvelsBusinessException("新增失败");
			}
		}
	}

	@Override
	public byte[] downLoadVisitFile(McfeOverdueCollectionCollectionVisitDTO dto) throws MarvelsBusinessException {
		McfeOverdueCollectionCollectionVisitDTO visitDTO=visitMapper.selectById(dto.getId());
		if(null==visitDTO){
			throw new MarvelsBusinessException("数据不存在");
		}
		String filepath=visitDTO.getFilePath();
		if(!new File(filepath).exists()){
			throw new MarvelsBusinessException("文件不存在");
		}
		dto.setFileName(visitDTO.getFileName());
		File file=new File(filepath);
		ByteArrayOutputStream  byteArrayOutputStream=null;
		FileInputStream inputStream=null;
		try {
			inputStream=new FileInputStream(file);
			byteArrayOutputStream =new ByteArrayOutputStream ();
			byte[] bs=new byte[1024];
			int n;    
			while ((n=inputStream.read(bs))!=-1) {
				byteArrayOutputStream.write(bs, 0, n);
			}
			return byteArrayOutputStream.toByteArray();
		} catch (IOException e) {
			MarvelsLogUtil.getInstance().error(">>>>>读取文件异常",e);
			throw new MarvelsBusinessException("读取文件异常",e);
		}finally {
			try {
				if(inputStream != null){
					inputStream.close();
				}
				if(byteArrayOutputStream != null){
					byteArrayOutputStream.close();
				}
			} catch (IOException e) {
				MarvelsLogUtil.getInstance().error(">>>>>流关闭异常异常",e);
			}
		}
	}

	@Override
	public MarvelsResultDTO uploadCollectVisitInfo(McfeOverdueCollectionCollectionVisitDTO dto) throws MarvelsBusinessException {
		String fileName=dto.getFile().getOriginalFilename();
		String basePath=CommonProperties.getUploadBasepath();
		String prefixPath=basePath+MarvelsConstant.UPLOAD_FILE_PATH_EXL+DateUtils.getCurrentSpecificate();
		if(!new File(prefixPath).isDirectory()){
			new File(prefixPath).mkdirs();
		}
		String filePath=prefixPath+"/"+new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+fileName;
		File file=new File(filePath);
		byte[] bs=new byte[1024];
		FileOutputStream fileOutputStream=null;
		InputStream inputStream=null;
		try {
			inputStream=dto.getFile().getInputStream();
			fileOutputStream=new FileOutputStream(file);
			int byteread = 0;  
	        // byteread表示一次读取到buffers中的数量。  
	        while ((byteread =inputStream.read(bs)) != -1) {  
	        	fileOutputStream.write(bs, 0, byteread);  
	        }  
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error(">>>>>写入文件异常",e);
		}finally {
			try {
				if(fileOutputStream != null){
					fileOutputStream.close();
				}
				if(inputStream != null){
					inputStream.close();
				}
				
			} catch (IOException e) {
				MarvelsLogUtil.getInstance().error(">>>>>流关闭异常异常",e);
			}
		}
		Map<String, Object> map=new HashMap<>();
		map.put("filePath", filePath);
		map.put("fileName", fileName);
		return MarvelsResultDTO.getResult(MarvelsErrorCode.SUCCESS.getValue(), MarvelsErrorCode.SUCCESS.getDesc(), map);
	}

	public Map<String, Object> selectBasicInfo(CollectListConditionDTO coditionDto) throws MarvelsBusinessException {
		String loanId=coditionDto.getLoanId();
		String overdueCode=coditionDto.getOverdueCode();
		//1.查询客户基本信息
		McamLoanApplyInfoDTO applyInfo = new McamLoanApplyInfoDTO();
		applyInfo.setLoanId(loanId);
		applyInfo = consumerApproveApi.selectLoanApplyInfo(applyInfo);
		//2.查询融资合同信息、逾期基本信息
		OverDueCollectContractDTO contractInfo = mcfeOverdueManageMapper.selectContractInfo(loanId);
		//3.行动
		List<McfeCollecteActionRecordDTO> actionRecords =  mcfeOverdueManageMapper.selectCollectRecordList(overdueCode);
		Map<String, Object> result = new HashMap<String, Object>();
		//4.查询逾期期数
		OverDueCollectContractDTO overDueTerm = mcfeOverdueManageMapper.selectOverDueTermNo(loanId);
		if(overDueTerm!=null){
			contractInfo.setFirstOverDueTermNo(overDueTerm.getFirstOverDueTermNo());
			contractInfo.setCurrOverDueTermNo(overDueTerm.getCurrOverDueTermNo());
		}
		List<McamLoanApplyInfoDTO> applyInfoList = new ArrayList<McamLoanApplyInfoDTO>();
		applyInfoList.add(applyInfo);
		result.put("applyInfo", applyInfoList);
		result.put("contractInfo", contractInfo);
		result.put("actionRecords", actionRecords);
		return result;
	}
	public CollectAccountDTO selectAccountInfo(CollectListConditionDTO coditionDto) throws MarvelsBusinessException {
		//账户信息
		CollectAccountDTO acctAccountInfo = mcfeOverdueManageMapper.selectAccountInfo(coditionDto.getLoanId());
		MarvelsLogUtil.getInstance().info(">>>>>>>>>催收管理查询融资信息--账户信息为"+acctAccountInfo);
		if(acctAccountInfo==null){
			acctAccountInfo = new CollectAccountDTO();
		}
		acctAccountInfo.setCustomerId(coditionDto.getCustIdNumber());
		return acctAccountInfo;
	}
	

	public PageInfo<OverDueTransInfoDTO> selectTransList(CollectListConditionDTO coditionDto) throws MarvelsBusinessException {
		Integer pageNum = coditionDto.getPageNum();
		if(pageNum==null||pageNum==0){
			pageNum =PageConstant.CURRPAGE; 
		}
		
		Integer pageSize = coditionDto.getPageSize();
		if(pageSize==null||pageSize==0){
			pageSize = PageConstant.PAGESIZE;
		}
		PageHelper.startPage(pageNum, pageSize);
		
		List<OverDueTransInfoDTO> list = mcfeOverdueManageMapper.selectTransList(coditionDto.getCustIdNumber());
		PageInfo<OverDueTransInfoDTO> pageInfo = new PageInfo<OverDueTransInfoDTO>(list);
		return pageInfo;
	}

	public OverDueTransInfoDTO selectTransInfoDetail(String id) throws MarvelsBusinessException {
		OverDueTransInfoDTO overDueTransInfoDto = mcfeOverdueManageMapper.selectTransInfoDetail(id);
		if(overDueTransInfoDto!=null){
			McamLoanApplyInfoDTO applyInfo = new McamLoanApplyInfoDTO();
			applyInfo.setLoanId(overDueTransInfoDto.getLoanId());
			applyInfo = consumerApproveApi.selectLoanApplyInfo(applyInfo);
			overDueTransInfoDto.setCustomerId(applyInfo.getCustCode());
		}
		return overDueTransInfoDto;
	}

	@Override
	public Page<McfeCollecteActionRecordDTO> actionInfoList(McfeCollecteActionRecordDTO dto)
			throws MarvelsBusinessException {
		if(dto.getPageNum()<1){
			dto.setPageNum(PageConstant.CURRPAGE);
		}
		if(dto.getPageSize()<1){
			dto.setPageSize(PageConstant.PAGESIZE);
		}
		PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
		return recordDao.actionList(dto);
	}

	@Override
	public CaseInfoDTO caseInfo(CaseInfoDTO dto) throws MarvelsBusinessException {
		return overdueMapper.caseInfo(dto);
	}

	@Override
	public Page<McfeCustomerLoanContractDTO> financingContract(CommonConditionDTO commonDTO) throws MarvelsBusinessException {
		int pageSize=commonDTO.getPageSize();
		int pageNum=commonDTO.getCurrentPage();
		if ( pageSize< 1) {
			pageSize=PageConstant.PAGESIZE;
		}
		if (pageNum< 1) {
			pageNum=PageConstant.CURRPAGE;
		}
		PageHelper.startPage(pageNum,pageSize);
		Page<McfeCustomerLoanContractDTO> dto=contractDao.selectByCustIdNumber(commonDTO.getCustCardNo());
		return dto;
	}

	@Override
	public Page<McfeCustomerRepaymentPlanDTO> planList(CommonConditionDTO dto) {
		int pageSize=dto.getPageSize();
		int pageNum=dto.getCurrentPage();
		if ( pageSize< 1) {
			pageSize=PageConstant.PAGESIZE;
		}
		if (pageNum< 1) {
			pageNum=PageConstant.CURRPAGE;
		}
		PageHelper.startPage(pageNum,pageSize);
		return planDao.selectAllPlan(dto.getLoanId());
	}

	@Override
	public void saveTransferInfo(CollectTransferDTO collectTransferDTO) throws MarvelsBusinessException {
		if(StringUtils.isEmpty(collectTransferDTO.getCheckOverdueCode()) || StringUtils.isEmpty(collectTransferDTO.getChoiceUser())){
			throw new MarvelsBusinessException("传入参数缺失");
		}
		List<String> checkOverdueList = Arrays.asList(collectTransferDTO.getCheckOverdueCode().split(","));
		for (String overdueCode : checkOverdueList) {
			if(StringUtils.isNotEmpty(overdueCode)){
				McfeOverdueCollectionDTO param = new McfeOverdueCollectionDTO();
				param.setOverdueCode(overdueCode);
				param.setAssignee(collectTransferDTO.getChoiceUser());
				collectMapper.updateTransferAssignee(param);
			}
		}
	}

	/**
	 * 更新催收处理最后操作时间
	 */
	@Override
	public void updateCollecteDate(CollectListConditionDTO condition) throws MarvelsBusinessException {
		UserDTO user = CacheUtils.getCacheUser();
		McfeOverdueCollectionDTO collectDTO=new McfeOverdueCollectionDTO();
		collectDTO.setOverdueCode(condition.getOverdueCode());
		collectDTO.setUpdatedDate(new Date());
		collectDTO.setUpdatedBy(user.getUserCode());
		int countCollect=collectMapper.updateByOverdueCode(collectDTO);
		if(countCollect<1){
			throw new MarvelsBusinessException("持久化催收信息失败");
		}
	}

	@Override
	public List<OnlineDeductionDto> onlineDeductionList(String loanIds, String channel) throws MarvelsBusinessException {
		if(StringUtils.isEmpty(loanIds)){
			throw new MarvelsBusinessException("请选择需要操作的单据");
		}
		List<String> loanList = Arrays.asList(loanIds.split(","));
		List<OnlineDeductionDto> list = null;
		
		if(StringUtils.equalsIgnoreCase("Y", CommonProperties.getNewRepaymentFlag())) {
			list = collectMapper.newOnlineDeductionList(loanList);
		}else {
			list = collectMapper.onlineDeductionList(loanList);
		}
		
		for (OnlineDeductionDto onlineDeductionDto : list) {
			McfePaymentUserBindCard param = new McfePaymentUserBindCard();
			param.setIdno(onlineDeductionDto.getCustIdNumber());
			param.setChannel(channel);
			List<Map<String, Object>> paymentBankList = handleWithholdApi.queryUserBankList(param);
			onlineDeductionDto.setPaymentBankList(paymentBankList);
			//默认显示卡
			for (Map<String, Object> bank : paymentBankList) {
				 // 如果有默认卡，则默认选中默认卡，否则默认选中第一张卡
				if(bank.get("defaultCard") != null && "1".equals(bank.get("defaultCard").toString())){
					onlineDeductionDto.setPaymentBankId(bank.get("id").toString());
					break;
				}else{
					onlineDeductionDto.setPaymentBankId(bank.get("id").toString());
				}
			}
		}
		return list;
	}

	@Override
	public void overdueSmsReminder(String loanIds) throws MarvelsBusinessException {
		if(StringUtils.isEmpty(loanIds)){
			throw new MarvelsBusinessException("请选择需要操作的进件单号");
		}
		List<String> loanList = Arrays.asList(loanIds.split(","));
		for(String loanId:loanList){
			//先判断该笔进件是否在待还款状态
			McfeCustomerLoanContractDTO dto=contractDao.selectContractByLoanId(loanId);
			if(dto.getStatus()==2 || dto.getStatus()==3){
				MarvelsLogUtil.getInstance().info(">>>>>loanId："+loanId+"逾期短信提醒不处于待还款状态");
				continue;
			}
			Map<String, Object> map=collectMapper.selectOverdueSms(loanId);
			MarvelsLogUtil.getInstance().info(">>>>loanId:"+loanId+",放款成功发送短信开始");
			net.sf.json.JSONObject jsonObject=new net.sf.json.JSONObject();
			jsonObject.put("phone", map.get("phone"));
			jsonObject.put("template_id", "6");
			jsonObject.put("src", "overdue");
			jsonObject.put("create_time",DateUtils.getDateYYYY_MM_DD_HH_MM_SS(new Date()));
			jsonObject.put("userName", map.get("userName"));
			jsonObject.put("expireDay",String.valueOf(map.get("expireDay")));
			jsonObject.put("overdueDay", map.get("overdueDay"));
			String digitsNumber=String.valueOf(map.get("digitsNumber"));
			jsonObject.put("totalAmount", map.get("totalAmount"));
			int size=digitsNumber.length();
			jsonObject.put("digitsNumber", digitsNumber.substring(size-4,size));
			jsonObject.put("bankCard", map.get("bankCard"));
			smsService.sendSms(jsonObject);
		}
	}

}
